<?php
/**
 * Create link
 *
 * PHP version 5
 *
 * @category Controller
 * @version  1.0
 * @author   Duonght <hduongdmit@gmail.com>
 */
App::uses('AppController', 'Controller');
class CreateLinkController extends AppController {

	public $uses = 'CreateLink';
	private $categorymulti = array();
	private $stt = -1;

	public function create($id = null){
		$this->layout = 'create_link';
		//get category type confige
		$category_type = Configure::read('category_type');
		$this->set('category_type', $category_type);
		//get all categories from database
		$listCategory = $this->CreateLink->getListCategory();
		$categories = array();
		foreach ($listCategory as $key => $category){
			$categorys = $category['categories_multi'];
			$categories[$categorys['cat_parent_id']][$categorys['id']] = $categorys;
		}

		$this->_sortLevel($categories);
		//view
		$this->set('id', $id);
		$this->set('datas', $this->categorymulti);
	}

	/**
	 * ajax tao link khi chon category
	 */
	public function createLinkCategory(){
		$this->layout = null;
		if ($this->request->is('post')) {
			$params = $this->request->data;
			$iCat = $params['iCat'];
			if ($iCat == 0) return;
			$items = $this->CreateLink->getListNews($iCat);
			$this->set('items', $items);
		}

		$this->render('create_ajax_link');
	}

	/**
	 * Sap xep danh muc theo level
	 *
	 * @param array $arrayCategory
	 * @param number $keystart nút cha
	 * @param number $level
	 */
	private function _sortLevel($arrayCategory, $keystart = 0, $level = -1){
		//kiểm tra xem tồn tại record không
		if (array_key_exists($keystart, $arrayCategory)) {
			$level++;
			foreach ($arrayCategory[$keystart] as $key => $value){

				//gán các phần tử cho array menu sắp xếp theo đúng vị trí
				//tang so thu tu
				$this->stt++;
				$this->categorymulti[$this->stt] = $value;

				//gan level cho menu
				$this->categorymulti[$this->stt]['level'] = $level;

				//thiet lap de biet day la` 1 nut cha
				if (array_key_exists($key, $arrayCategory)){
					$this->categorymulti[$this->stt]["parent"] = 1;
				} else {
					$this->categorymulti[$this->stt]["parent"] = 0;
				}

				//de quy de lap lai, neu menu_id nam trong array cac menu cha
				$this->_sortLevel($arrayCategory, $key, $level);
			}
		}
	}


}
